import { HttpException, HttpStatus, Injectable, NotFoundException } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { CreatePropositionDto, CommentType, GetCommentType, LikeType } from './dto/create-proposition.dto'
// import { UpdatePropositionDto } from './dto/update-proposition.dto'
import { Proposition, PropositionDocument } from '../model/proposition.schema'
import { Comment, commentDocument } from '../model/comment.schema'
import { Collect, CollectDocument } from '../model/collect.schema'
import { Like, LikeDoucment } from '../model/like.schema'
import { Bar, BarDocument } from '../model/bar.schema'
@Injectable()
export class PropositionService {
  constructor(
    @InjectModel(Proposition.name) private readonly proposition: Model<PropositionDocument>,
    @InjectModel(Comment.name) private readonly comment: Model<commentDocument>,
    @InjectModel(Collect.name) private collect: Model<CollectDocument>,
    @InjectModel(Like.name) private likeSchema: Model<LikeDoucment>,
    @InjectModel(Bar.name) private barSchema: Model<BarDocument>,
  ) {}
  /* 
    创建帖子
  */
  async create(createPropositionDto: CreatePropositionDto) {
    const result = await this.proposition.create(createPropositionDto)
    //更新帖子数量
    const bar = await this.barSchema.findById(createPropositionDto.bar)
    bar.propositionCount = await this.proposition.countDocuments({ bar: createPropositionDto.bar })
    await bar.save()
    const info = await this.proposition
      .findById({ _id: result._id }, '-__v -createdAt -updatedAt')
      .populate('user', '-__v -createdAt -updatedAt -phone -password')

    return {
      data: info,
      code: 200,
      message: '创建成功',
    }
  }

  /* 查找当前贴吧下的所有帖子 */
  async findAll(barId: string, info: { page: number; pagesize: number; name: string }) {
    const { page = 1, pagesize = 10, name = null } = info
    let allTip
    //模糊搜索  是否搜索
    if (!name) {
      allTip = await this.proposition
        .find({ bar: barId }, '-__v -createdAt -updatedAt')
        .skip((page - 1) * pagesize)
        .limit(pagesize)
        .populate('user', '-__v -createdAt -updatedAt -phone -password')
        .orFail(new NotFoundException('Not find!'))
      return {
        count: await this.proposition.countDocuments({ bar: barId }),
        allTip,
      }
    } else {
      allTip = await this.proposition
        .find({ title: { $regex: name, $options: 'i' } }, '-__v -createdAt -updatedAt')
        .skip((page - 1) * pagesize)
        .limit(pagesize)
        .populate('user', '-__v -createdAt -updatedAt -phone -password')
        .orFail(new NotFoundException('Not find!'))
      return {
        allTip,
        count: allTip.length,
      }
    }
  }

  /* 删除帖子 */
  async deleteProposition(id: string) {
    const result = await this.proposition.findOne({ _id: id }).orFail(new NotFoundException('Not find!'))
    await result.remove()
    return result
  }

  /* 发表评论 */
  async Pubcomment(comment: CommentType, id: string) {
    const back = await this.comment.create({ user: id, content: comment.content, proposition: comment.proposition })
    const find = await this.comment
      .findById({ _id: back._id }, '-__v -createdAt -updatedAt')
      .orFail(new NotFoundException('Not find!'))
    //统计一次评论数量
    const proposition = await this.proposition.findById(comment.proposition)
    proposition.commentCount = await this.comment.countDocuments({ proposition: comment.proposition })
    await proposition.save()
    return find
  }

  /* 获取当前帖子下的所有评论 */
  async getComment(params: GetCommentType, userID: string | null) {
    const { page = 1, pagesize = 10, proposition } = params

    const commentList = await this.comment
      .find({ proposition: proposition }, 'content _id isLike')
      .skip((page - 1) * pagesize)
      .limit(pagesize)
      .populate('user', 'username photo')
      .orFail(new NotFoundException('params err'))
    if (!userID) {
      //登录状态
      return {
        commentList,
        count: await this.comment.countDocuments({ proposition }),
      }
    } else {
      //未登录
      commentList.forEach(async (doc) => {
        const like = await this.likeSchema.findOne({ user: userID, comment: doc._id.toString() })

        if (like) {
          //当前用户给该评论点赞了
          doc.isLike = true
        }
      })

      return {
        commentList,
        count: await this.comment.countDocuments({ proposition }),
      }
    }
  }

  /* 删除评论 */
  async deleteComment(info: { user: string; comment: string }) {
    //如果删除的人不是这条评论的发起人则不能删除
    await this.comment.findOne({ user: info.user, _id: info.comment }).orFail(new NotFoundException('权限不足'))

    //删除逻辑
    const back = await this.comment.findById(info.comment)
    await back.remove()
    return {
      data: back.content,
      code: 200,
      message: '该评论已经被删除',
    }
  }

  /* 搜藏帖子 */
  async collectProposition(info: { user: string; proposition: string }) {
    //去重
    const find = await this.collect.findOne({ user: info.user, proposition: info.proposition })
    const proposition = await this.proposition.findById(info.proposition)
    let isCollect = false

    if (find) {
      //已收藏该帖子 , 修改状态为取消收藏

      await this.collect.findByIdAndDelete(find._id)
      //减少收藏数量
      proposition.beCollectCount = await this.collect.countDocuments({ proposition: info.proposition })
      await proposition.save()
      return {
        data: { isCollect },
        code: 200,
        message: '取消收藏成功',
      }
    } else {
      isCollect = true
      await this.collect.create({ user: info.user, proposition: info.proposition })
      proposition.beCollectCount = await this.collect.countDocuments({ proposition: info.proposition })
      await proposition.save()
      return {
        data: { isCollect },
        code: 200,
        message: '收藏成功',
      }
    }
  }

  /* 给评论或者帖子点赞 */
  async like(info: LikeType) {
    const { proposition, user, comment } = info
    let isLike = false
    let back
    if (proposition) {
      const findProposition = await this.proposition.findById(proposition)
      const like = await this.likeSchema.findOne({ proposition, comment: null })
      if (like) {
        //表示已经是喜欢状态 取消喜欢
        await this.likeSchema.findByIdAndDelete(like._id)
        //统计点赞数
        findProposition.likeCount = await this.likeSchema.countDocuments({ user: user, proposition, comment: null })
        await findProposition.save()
        isLike = false
        return {
          data: back,
          code: 200,
          isLike,
          message: '取消点赞成功',
        }
      } else {
        //未点击喜欢
        back = await this.likeSchema.create({ user, proposition })
        findProposition.likeCount = await this.likeSchema.countDocuments({ user: user, proposition, comment: null })
        await findProposition.save()
        isLike = true
        return {
          data: back,
          code: 200,
          isLike,
          message: '点赞成功',
        }
      }
    } else if (comment) {
      const findComment = await this.comment.findById(comment)
      const like = await this.likeSchema.findOne({ comment, proposition: null })
      if (like) {
        //表示已经是喜欢状态 取消喜欢
        await this.likeSchema.findByIdAndDelete(like._id)
        //统计点赞数
        findComment.likeCount = await this.likeSchema.countDocuments({ user: user, comment, proposition: null })
        await findComment.save()
        isLike = false
        return {
          data: back,
          code: 200,
          isLike,
          message: '取消点赞成功',
        }
      } else {
        //未点击喜欢
        back = await this.likeSchema.create({ user, comment })
        findComment.likeCount = await this.likeSchema.countDocuments({ user: user, comment, proposition: null })
        await findComment.save()
        isLike = true
        return {
          data: back,
          code: 200,
          isLike,
          message: '点赞成功',
        }
      }
    } else {
      throw new HttpException('params err', HttpStatus.BAD_REQUEST)
    }
  }

  /* 获取帖子详情 (已登录 or 未登录) */
  async getPropositionInfoByToken(propositionID: string, userID: string | null) {
    const proposition = await this.proposition
      .findById(propositionID)
      .populate('user', 'username photo')
      .populate('bar', 'barName barLogo description')
      .orFail(new NotFoundException('not find proposition'))
    let isLike = false //是否点击喜欢
    let isCollect = false //是否点击收藏
    if (userID) {
      //登录状态
      const like = await this.likeSchema.findOne({ user: userID, proposition: propositionID })
      const collect = await this.collect.findOne({ user: userID, proposition: propositionID })
      if (like) {
        isLike = true
      }
      if (collect) {
        isCollect = true
      }
      return {
        data: { proposition, isLike, isCollect },
        code: 200,
        message: '获取成功',
      }
    } else {
      //未登录状态
      return {
        data: { proposition, isLike, isCollect },
        code: 200,
        message: '获取成功',
      }
    }
  }
}
